#coding: utf-8

__author__ = 'vlasovai'

from django.views.generic import TemplateView

from okno.models import Citizen
from models import Roditel, Det

class CompareView(TemplateView):

    template_name = 'compare/compare.html'

    def _compare(self, arm_obj, asp_obj):
        data = { 'code': arm_obj.code }

        data['f_ok'] = False
        data['f'] = arm_obj.f
        if asp_obj.famil and arm_obj.f == asp_obj.famil.lower():
            data['f_ok'] = True

        data['i_ok'] = False
        data['i'] = arm_obj.i
        if asp_obj.imja and arm_obj.i == asp_obj.imja.lower():
            data['i_ok'] = True

        data['o_ok'] = False
        data['o'] = arm_obj.o
        if asp_obj.otch and arm_obj.o == asp_obj.otch.lower():
            data['o_ok'] = True

        data['dat_ok'] = False
        data['dat'] = arm_obj.dat
        if asp_obj.drog and arm_obj.dat == asp_obj.drog.date():
            data['dat_ok'] = True

        data['psr_ok'] = False
        data['psr'] = arm_obj.psr
        if asp_obj.psr and arm_obj.psr == asp_obj.psr.strip():
            data['psr_ok'] = True

        data['asp_psr'] = asp_obj.psr

        data['pnm_ok'] = False
        data['pnm'] = arm_obj.pnm
        if asp_obj.pnm and arm_obj.pnm == asp_obj.pnm.strip():
            data['pnm_ok'] = True

        data['asp_pnm'] = asp_obj.pnm

        data['addr_arm'] = arm_obj.addr
        try:
            data['addr_asp'] = asp_obj.address
        except Exception:
            data['addr_asp'] = None

        return data

    def _not_found(self, arm_obj):

        data = {
            'code': arm_obj.code,
            'f_ok': False,
            'f': arm_obj.f,
            'i_ok': False,
            'i': arm_obj.i,
            'o_ok': False,
            'o': arm_obj.o,
            'psr_ok': False,
            'psr': arm_obj.psr,
            'pnm_ok': False,
            'pnm': arm_obj.pnm,
            'asp_psr': None,
            'asp_pnm': None,
            'dat_ok': False,
            'dat': arm_obj.dat,
            'addr_arm': arm_obj.addr,
            'addr_asp': None
        }

        return data

    def get_context_data(self, **kwargs):
        offset = int(self.kwargs['offset'])

        context = super(CompareView, self).get_context_data(**kwargs)
        context['offset'] = offset

        data = list()

        start = offset*500
        end = offset*500+499
        for item in Roditel.objects.all()[start:end]:
            found = False
            #Сначала ищем по полным ФИО
            obj = Citizen.objects.filter(famil__startswith=item.f[0:8],
                imja__startswith=item.i[0:8], otch__startswith=item.o[0:8])

            if len(obj) > 0: #Нашли. Выбираем нужного
                if len(obj) == 1: #Совпадение единственное. Сверяем данные
                    data.append(self._compare(item, obj[0]))
                    found = True

                else:
                    for __item in obj:
                        if item.pnm == __item.pnm or (__item.drog and item.dat == __item.drog.date()):
                            data.append(self._compare(item, __item))
                            found = True
                            break


            else: #Точного совпадения нет. Ищем другими путями
                #Ищем по паспорту
                obj = Citizen.objects.filter(pnm=item.pnm)
                for __item in obj:
                    if __item.psr.strip() == item.psr:
                        data.append(self._compare(item, __item))
                        found = True
                        break

                if not found: #По паспорту не нашли
                    data.append(self._not_found(item))

        context['data'] = data

        #raise Exception(data)
        return context

class CompareDetView(TemplateView):

    template_name = 'compare/compare_det.html'

    def _compare(self, arm_obj, asp_obj):
        data = { 'code': arm_obj.code }

        data['f_ok'] = False
        data['f'] = arm_obj.f
        if asp_obj.famil and arm_obj.f == asp_obj.famil.lower():
            data['f_ok'] = True

        data['i_ok'] = False
        data['i'] = arm_obj.i
        if asp_obj.imja and arm_obj.i == asp_obj.imja.lower():
            data['i_ok'] = True

        data['o_ok'] = False
        data['o'] = arm_obj.o
        if asp_obj.otch and arm_obj.o == asp_obj.otch.lower():
            data['o_ok'] = True

        data['dat_ok'] = False
        data['dat'] = arm_obj.dat
        if asp_obj.drog and arm_obj.dat == asp_obj.drog.date():
            data['dat_ok'] = True

        return data

    def _not_found(self, arm_obj):

        data = {
            'code': arm_obj.code,
            'f_ok': False,
            'f': arm_obj.f,
            'i_ok': False,
            'i': arm_obj.i,
            'o_ok': False,
            'o': arm_obj.o,
            'dat_ok': False,
            'dat': arm_obj.dat
        }

        return data

    def get_context_data(self, **kwargs):
        offset = int(self.kwargs['offset'])

        context = super(CompareDetView, self).get_context_data(**kwargs)
        context['offset'] = offset

        data = list()

        start = offset*500
        end = offset*500+499
        for item in Det.objects.all()[start:end]:
            found = False
            #Сначала ищем по полным ФИО
            if item.o:
                obj = Citizen.objects.filter(famil__startswith=item.f[0:8],
                    imja__startswith=item.i[0:8], otch__startswith=item.o[0:8])

                if len(obj) > 0: #Нашли. Выбираем нужного
                    if len(obj) == 1: #Совпадение единственное. Сверяем данные
                        data.append(self._compare(item, obj[0]))
                        found = True

                    else:
                        for __item in obj:
                            if __item.drog and item.dat == __item.drog.date():
                                data.append(self._compare(item, __item))
                                found = True
                                break
            else: #Отчество не указано. Ищем без него по дате рождения
                obj = Citizen.objects.filter(famil__startswith=item.f[0:8],
                    imja__startswith=item.i[0:8])

                for __item in obj:
                    if not __item.drog:
                        continue

                    dat = __item.drog.date()
                    if item.dat == dat:
                        data.append(self._compare(item, __item))
                        found = True
                        break

            if not found: #Ничего не нашли
                data.append(self._not_found(item))

        context['data'] = data

        #raise Exception(data)
        return context